/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: TradeFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.ui.HistoryEntrustOrderFragment;
import io.bhex.app.market.ui.CoinDialogFragment;
import io.bhex.app.trade.adapter.OpenOrdersAdapter;
import io.bhex.app.trade.presenter.TradeFragmentPresenter;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CoinUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.pop.FitPopupWindow;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.account.EventLogin;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.trade.bean.OrderBean;

/**
 * ================================================
 * 描   述：币币交易
 * ================================================
 */

public class TradeFragment extends BaseTradeFragment<TradeFragmentPresenter, TradeFragmentPresenter.TradeFragmentUI> implements TradeFragmentPresenter.TradeFragmentUI{

    private static final String TAG = "TradeFragment";
    private TextView tradeTotalMoney;
    private TextView tradeTotalMoneyTitle;
    private ArrayList<Pair<String, Fragment>> items;


    private OpenOrdersAdapter openOrdersAdapter;
    private HistoryEntrustOrderFragment.HistoryEntrustAdapter historyEntrustAdapter;

    private List<OrderBean> currentOrderDatas = new ArrayList<>();
    private List<OrderBean> historyOrderDatas = new ArrayList<>();
    private boolean isShowCumulativeVolume = false;


    @Override
    protected TradeFragmentPresenter.TradeFragmentUI getUI() {
        return this;
    }

    @Override
    protected TradeFragmentPresenter createPresenter() {
        return new TradeFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_trade_layout, null, false);
    }

    @Override
    protected void initInstanceView() {
        topBar.setTitleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager childFragmentManager = getFragmentManager();
                CoinDialogFragment coinDialogFragment = new CoinDialogFragment(coinPairBean, new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 180.0f, 0.0f);
                        getPresenter().getTicker();
                    }
                });

                coinDialogFragment.show(childFragmentManager, "dialog");
                QuoteApi.UnSubTickers();
                AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 0.0f, 180.0f);

            }
        });
        headerView.findViewById(R.id.trade_money_ll).setVisibility(View.VISIBLE);
        headerView.findViewById(R.id.option_money_ll).setVisibility(View.GONE);

        tradeTotalMoneyTitle = headerView.findViewById(R.id.trade_total_money_title);
        tradeTotalMoney = headerView.findViewById(R.id.trade_total_money);

        openOrdersAdapter = new OpenOrdersAdapter(currentOrderDatas);
        //openOrdersAdapter.showCoinPairName(false);
        openOrdersAdapter.isFirstOnly(false);
        //openOrdersAdapter.addHeaderView(headerView);

        isShowCumulativeVolume = MMKVManager.getInstance().loadBookQuantityShowMode();


        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View emptyView = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(200);
//        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        emptyView.setLayoutParams(layoutParams);
        openOrdersAdapter.setHeaderFooterEmpty(true, true);
        openOrdersAdapter.setEmptyView(emptyView);

        openOrdersAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.revoke_order && adapter.getData()!= null && position < adapter.getData().size()) {
                    OrderBean itemModel = (OrderBean) adapter.getData().get(position);
                    getPresenter().cancelOrder(itemModel.getOrderId());
                }
            }
        });
        recyclerView.setAdapter(openOrdersAdapter);
        historyEntrustAdapter = new HistoryEntrustOrderFragment.HistoryEntrustAdapter(getActivity(), historyOrderDatas);
        historyEntrustAdapter.isFirstOnly(false);
        //historyEntrustAdapter.addHeaderView(headerView);

        View emptyView2 = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
        ViewGroup.LayoutParams layoutParams2 = emptyView2.getLayoutParams();
        layoutParams2.height = PixelUtils.dp2px(200);
        emptyView2.setLayoutParams(layoutParams2);
        historyEntrustAdapter.setHeaderFooterEmpty(true, true);
        historyEntrustAdapter.setEmptyView(emptyView2);
        historyEntrustAdapter.setOnLoadMoreListener(this, recyclerView);
        historyEntrustAdapter.setEnableLoadMore(true);

        balanceAvailableAboutTx.setVisibility(View.VISIBLE);
        btnTransfer.setVisibility(View.GONE);

        initTabs();
    }

    private void initTabs() {
        items = new ArrayList<>();
        items.add(new Pair<String, Fragment>(getString(R.string.string_current_entrust), null));
        items.add(new Pair<String, Fragment>(getString(R.string.string_history_entrust), null));

        OrderAdapter adapter = new OrderAdapter(getChildFragmentManager());
        ViewPager viewPager = headerView.findViewById(R.id.clViewPager);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.color_black));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position == 0) {
                    /*historyEntrustAdapter.removeAllHeaderView();
                    openOrdersAdapter.addHeaderView(headerView);
                    */recyclerView.setAdapter(openOrdersAdapter);
                }
                else if(position == 1) {
                    /*openOrdersAdapter.removeAllHeaderView();
                    historyEntrustAdapter.addHeaderView(headerView);
                    */recyclerView.setAdapter(historyEntrustAdapter);
                    getPresenter().getHistoryEntrustOrders(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        CommonUtil.setUpIndicatorWidthByReflex(tabLayout,15,15);
    }

    private class OrderAdapter extends FragmentPagerAdapter {

        public OrderAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return items.get(position).second;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(coinPairBean == null){
            CoinPairBean bbTradeCoin = CoinUtils.getBBTradeCoin();
            if (bbTradeCoin != null) {
                coinPairBean = bbTradeCoin;
            }else{
                coinPairBean = SymbolDataManager.GetInstance().getDefaultTradeCoinPair();
            }
        }

        EventBus.getDefault().register(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMessageEvent(CoinPairBean postCoinPairBean) {
        if(postCoinPairBean == null)
            return;
        if (KlineUtils.isSymbolOfBB(postCoinPairBean.getCoinType())) {
            coinPairBean = postCoinPairBean;
            String oldSymbol = symbol;
            boolean needSwitchTradeTab = postCoinPairBean.isNeedSwitchTradeTab();
//        ToastUtils.showShort("Message "+needSwitchTradeTab);
            if (!needSwitchTradeTab) {
                if (!isFirst) {
                    return;
                }
            }
            isFirst = false;
            if(isBuyMode != postCoinPairBean.isBuyMode()){
                if (postCoinPairBean.isBuyMode()) {
                    AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
                } else {
                    AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
                }
            }
            loadDefaultConfig(postCoinPairBean);
            if (!oldSymbol.equals(postCoinPairBean.getSymbolId())) {
                switchBuySellTab(isBuyMode);
                updateUnit();
                getPresenter().resetAllData(postCoinPairBean);
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMessageEvent(EventLogin eventLogin) {
        switchBuySellTab(isBuyMode);
    }


    @Override
    public void onResume() {
        super.onResume();

        if (!UserInfo.isLogin()) {
            if (currentOrderDatas.size()>0) {
                currentOrderDatas.clear();
                if (openOrdersAdapter != null) {
                    openOrdersAdapter.setNewData(currentOrderDatas);
                }
            }
            if (historyOrderDatas.size()>0) {
                historyOrderDatas.clear();
                if (historyEntrustAdapter != null) {
                    historyEntrustAdapter.setNewData(historyOrderDatas);
                }
            }

        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        bookTitleAmount.setOnClickListener(this);

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (isVisible()) {
            isShowCumulativeVolume = MMKVManager.getInstance().loadBookQuantityShowMode();
            setBookTitleAmount();

            if (!UserInfo.isLogin()) {
                balanceAvailableTx.setText(getString(R.string.string_placeholder));
                currentOrderDatas.clear();
                if (openOrdersAdapter != null) {
                    openOrdersAdapter.notifyDataSetChanged();
                }
                historyOrderDatas.clear();
                if (historyEntrustAdapter != null) {
                    historyEntrustAdapter.notifyDataSetChanged();
                }
                return;
            }
        }

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.title_amount:
                showSelectBookQuantityTypeAlert();
                break;
        }
    }

    private void showSelectBookQuantityTypeAlert() {
        String[] quantityTypeArray = new String[]{getString(R.string.string_cumulative_quantity_format, baseTokenName),getString(R.string.string_amount_format, baseTokenName)};
        AlertView alertView = new AlertView(null, null, getString(R.string.string_cancel), quantityTypeArray, null, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isShowCumulativeVolume = true;
                    setBookTitleAmount();
                    getPresenter().changeBookQuantityShowMode(isShowCumulativeVolume);
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                }else if(position == 1){
                    isShowCumulativeVolume = false;
                    setBookTitleAmount();
                    getPresenter().changeBookQuantityShowMode(isShowCumulativeVolume);
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                }
            }
        });
        alertView.show();
    }

    private void setBookTitleAmount() {
        bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, baseTokenName));
    }


    private void showSelectBookQuantityType() {
        View selectQuantityTypeView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_select_book_quantity_type, null);
        FitPopupWindow selectQuantityTypePopupWindow = new FitPopupWindow(getActivity(), WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);


        TextView cumulateQuantity = selectQuantityTypeView.findViewById(R.id.cumulateQuantity);
        TextView quantity = selectQuantityTypeView.findViewById(R.id.quantity);

        cumulateQuantity.setText(getString(R.string.string_cumulative_quantity_format, baseTokenName));
        quantity.setText(getString(R.string.string_amount_format, baseTokenName));

        cumulateQuantity.setBackgroundColor(getResources().getColor(isShowCumulativeVolume ? R.color.color_bg_2 : R.color.color_bg_1));
        quantity.setBackgroundColor(getResources().getColor(isShowCumulativeVolume ? R.color.color_bg_1 : R.color.color_bg_2));

        cumulateQuantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowCumulativeVolume = true;
                bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, baseTokenName));
                selectQuantityTypePopupWindow.dismiss();
            }
        });

        quantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowCumulativeVolume = false;
                bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, baseTokenName));
                selectQuantityTypePopupWindow.dismiss();
            }
        });

        selectQuantityTypePopupWindow.setView(selectQuantityTypeView,bookTitleAmount);
        selectQuantityTypePopupWindow.show();
    }

    @Override
    public boolean isShowCumulativeVolume() {
        return isShowCumulativeVolume;
    }

    @Override
    protected void updateTradeAmountOfMoney() {
        if (!isLimitedPrice) {
            return;
        }
        String amount = editAmount.getText().toString();
//        String price = editPrice.getText().toString().trim();
        String price = priceLimitedView.getPrice();
        if (TextUtils.isEmpty(price) || TextUtils.isEmpty(amount)) {
            tradeTotalMoneyTitle.setText(getString(R.string.string_placeholder));
            tradeTotalMoney.setText(getString(R.string.string_placeholder));
            return;
        }
        double result = NumberUtils.mul(price, amount);
        String value = NumberUtils.roundFormatDown(String.valueOf(result), digitAmount);
        String legalMoney = RateDataManager.CurRatePrice(quoteToken, value);
        legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
        tradeTotalMoneyTitle.setText(value + quoteTokenName);
        tradeTotalMoney.setText("≈" + legalMoney);
//        tradeTotalMoney.setText(getString(R.string.string_amount_of_money_format, value, quoteTokenName, legalMoney));

    }

    @Override
    protected void switchPriceMode(boolean isLimitedPriceParams)
    {
        isLimitedPrice = isLimitedPriceParams;
        editAmount.setText("");
        if (isLimitedPrice) {
            priceMode.setText(getString(R.string.string_limited_price));
            priceAbout.setVisibility(View.VISIBLE);
            tradeTotalMoney.setVisibility(View.VISIBLE);
            tradeTotalMoneyTitle.setVisibility(View.VISIBLE);
        } else {
            priceMode.setText(getString(R.string.string_market_price));
            priceAbout.setVisibility(View.INVISIBLE);
            tradeTotalMoney.setVisibility(View.INVISIBLE);
            tradeTotalMoneyTitle.setVisibility(View.INVISIBLE);
        }

        updatePriceModeAssociatedView(isLimitedPrice);
        updateUnit();
    }

    @Override
    public void showOpenOrders(List<OrderBean> datas) {
        if (!UserInfo.isLogin()) {
            if (!currentOrderDatas.isEmpty()) {
                currentOrderDatas.clear();
                openOrdersAdapter.notifyDataSetChanged();
            }
            return;
        }
        if (datas != null) {
            currentOrderDatas.clear();
            currentOrderDatas.addAll(datas);
            openOrdersAdapter.notifyDataSetChanged();
        }

        loadEntrustOrdersPriceIntoCache(datas);
    }

    private String bidPrice = "";
    private String askPrice = "";
    private void loadEntrustOrdersPriceIntoCache(List<OrderBean> datas) {
        bidPrice = "";
        askPrice = "";
        if (datas != null) {
            for (OrderBean data : datas) {
                String price = data.getPrice();
                price = NumberUtils.stripTrailingZeros(price);
                if (KlineUtils.isBuyOrder(getActivity(),data.getSide())) {
                    bidPrice = bidPrice + price + ";";
                }else{
                    askPrice = askPrice + price + ";";
                }
            }
        }
    }

    public boolean isCurrentBidOrderPrice(String price){
        price = NumberUtils.stripTrailingZeros(price);
        return bidPrice.contains(price+";");
    }

    public boolean isCurrentAskOrderPrice(String price){
        price = NumberUtils.stripTrailingZeros(price);
        return askPrice.contains(price+";");
    }

    @Override
    public void showHistoryOrders(List<OrderBean> datas) {
        if (!UserInfo.isLogin()) {
            if (!historyOrderDatas.isEmpty()) {
                historyOrderDatas.clear();
                historyEntrustAdapter.notifyDataSetChanged();
            }
            return;
        }
        if (datas != null) {
            historyOrderDatas.clear();
            historyOrderDatas.addAll(datas);
            historyEntrustAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        getPresenter().loadMore();
    }

    @Override
    public void loadMoreComplete() {
        if (historyEntrustAdapter != null) {
            historyEntrustAdapter.loadMoreComplete();
        }
    }

    @Override
    public void loadMoreFailed() {
        if (historyEntrustAdapter != null) {
            historyEntrustAdapter.loadMoreFail();
        }
    }

    @Override
    public void loadEnd() {
        if (historyEntrustAdapter != null) {
            historyEntrustAdapter.loadMoreEnd();
        }
    }

    @Override
    protected void updatePriceModeAssociatedView(boolean isLimitedPrice) {
        if (isLimitedPrice) {
            priceLimitedView.setVisibility(View.VISIBLE);
            priceMarketTx.setVisibility(View.GONE);
        } else {
            priceLimitedView.setVisibility(View.GONE);
            priceMarketTx.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void updateUnit(){
        bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, baseTokenName));
        bookTitlePrice.setText(getString(R.string.string_price_ph, quoteTokenName));

        if (isBuyMode) {
            //买入
            if (isLimitedPrice) {
                //限价
                isQuoteToken = false;
                editAmount.setHint(getResources().getString(R.string.string_amount));
                editAmountUnit.setText(baseTokenName);
                updateAsset(quoteToken, quoteTokenName);
                updateStepViewRange(false, baseToken, baseTokenName);
            } else {
                //市价
                isQuoteToken = true;
                editAmount.setHint(getResources().getString(R.string.string_amount_of_money));
                editAmountUnit.setText(quoteTokenName);
                updateAsset(quoteToken, quoteTokenName);
                updateStepViewRange(true, quoteToken, quoteTokenName);
            }
        } else {
            //卖出
            if (isLimitedPrice) {
                //限价
                isQuoteToken = false;
                editAmount.setHint(getResources().getString(R.string.string_amount));
                editAmountUnit.setText(baseTokenName);
                updateAsset(baseToken, baseTokenName);
                updateStepViewRange(false, baseToken, baseTokenName);
            } else {
                //市价
                isQuoteToken = true;
                editAmount.setHint(getResources().getString(R.string.string_amount));
                editAmountUnit.setText(baseTokenName);
                updateAsset(baseToken, baseTokenName);
                updateStepViewRange(false, baseToken, baseTokenName);
            }
        }
    }

    @Override
    protected void updateStepViewRange(boolean isQuoteToken, String token, String tokenName) {
        if (isBuyMode) {//买入
            stepViewMaxValue = getQuoteTokenAsset();
            if (isLimitedPrice) {//限价
//                String price = editPrice.getText().toString().trim();
                String price = priceLimitedView.getPrice();
                if (!TextUtils.isEmpty(stepViewMaxValue) && !TextUtils.isEmpty(price)) {
//                    stepViewMaxValue = NumberUtils.div(price, getQuoteTokenAsset(), digitPrice) + "";
//                    stepViewMaxValue = NumberUtils.div(price, getQuoteTokenAsset(), AppData.DIGIT_MAX_NUM) + "";
                    stepViewMaxValue =NumberUtils.roundFormatDown(NumberUtils.div(price, getQuoteTokenAsset()),AppData.DIGIT_MAX_NUM);
                }
            } else {
                //市价 默认的是输入金额 所以最大为可用金额资产
            }
        } else {//卖出
            stepViewMaxValue = getBaseTokenAsset();
        }
        stepViewMinTx.setText("0");
        stepViewMaxTx.setText(getString(R.string.string_stepview_max_txt_format, NumberUtils.roundFormatDown(stepViewMaxValue, isQuoteToken ? digitPrice : digitBase), tokenName));
        updateStepViewValue(editAmount.getText().toString());
    }

    @Override
    protected  void createOrder(boolean isBuyMode){
        /**交易下单规则粗略校验**************/
//        String price = editPrice.getText().toString().trim();
        String price = priceLimitedView.getPrice();
        if (isLimitedPrice) {
            if (TextUtils.isEmpty(price)) {
                ToastUtils.showShort(getActivity(), getString(R.string.string_prompt_input_price));
                return;
            }
            if (Double.valueOf(price) <= 0) {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_price));
                return;
            }
        }

        String amount = editAmount.getText().toString().trim();
        if (TextUtils.isEmpty(amount)) {
            if (isBuyMode && !isLimitedPrice) {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount_of_money));
            } else {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount));
            }
            return;
        }
        if (Double.valueOf(amount) <= 0) {
            if (isBuyMode && !isLimitedPrice) {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount_of_money));
            } else {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount));
            }
            return;
        }
        if (coinPairBean != null) {
            //最小交易数量
            String minTradeQuantity = coinPairBean.getMinTradeQuantity();
            //最小交易额
            String minTradeAmount = coinPairBean.getMinTradeAmount();
            if (isLimitedPrice) {//限价
                String minPricePrecision = coinPairBean.getMinPricePrecision();
                //最小交易价格
                if (!TextUtils.isEmpty(minPricePrecision)) {
                    if (NumberUtils.sub(price, minPricePrecision) < 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_price, minPricePrecision)+quoteTokenName);
                        return;
                    }
                }

                //最小交易数量
                if (!TextUtils.isEmpty(minTradeQuantity)) {
                    if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_quantity, minTradeQuantity)+ baseTokenName);
                        return;
                    }
                }

                //最小交易额
                if (!TextUtils.isEmpty(minTradeAmount)) {
                    if (NumberUtils.sub(String.valueOf(NumberUtils.mul(price, amount)), minTradeAmount) < 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_amount, minTradeAmount)+quoteTokenName);
                        return;
                    }
                }
            } else {//市价
                if (isBuyMode) {
                    //最小交易额
                    if (!TextUtils.isEmpty(minTradeAmount)) {
                        //amount 为输入金额
                        if (NumberUtils.sub(amount, minTradeAmount) < 0) {
                            ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_amount, minTradeAmount)+quoteTokenName);
                            return;
                        }
                    }
                } else {
                    //最小交易数量
                    if (!TextUtils.isEmpty(minTradeQuantity)) {
                        if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                            ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_quantity, minTradeQuantity)+baseTokenName);
                            return;
                        }
                    }
                }

            }
        } else {
            ToastUtils.showShort(getActivity(), getString(R.string.string_retry_select_trade_symbol));
            return;
        }

        /** 最大交易额/量判断 **********/
        if (isBuyMode) {//买入
            if (isLimitedPrice) {//限价
                //最大交易额
                if (!TextUtils.isEmpty(getQuoteTokenAsset())) {
                    if (NumberUtils.sub(String.valueOf(NumberUtils.mul(price, amount)), getQuoteTokenAsset()) > 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough));
                        return;
                    }
                } else {
                    ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough_swipy_refresh));
                    return;
                }
            } else {//市价
                //最大交易额
                if (!TextUtils.isEmpty(getQuoteTokenAsset())) {
                    //amount 为输入金额
                    if (NumberUtils.sub(amount, getQuoteTokenAsset()) > 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough));
                        return;
                    }
                } else {
                    ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough_swipy_refresh));
                    return;
                }
            }

        } else {//卖出

            //最大交易数量
            if (!TextUtils.isEmpty(getBaseTokenAsset())) {
                if (NumberUtils.sub(amount, getBaseTokenAsset()) > 0) {
                    ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough));
                    return;
                }
            } else {
                ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough_swipy_refresh));
                return;
            }
        }

        //去下单
        getPresenter().createOrder(isBuyMode, isLimitedPrice, exchangeId, symbol, price, amount);

    }

}
